package com.demo.vert.io;

import com.alibaba.fastjson.JSON;
import lombok.extern.java.Log;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Base64;
import java.util.LinkedHashMap;

@Log
public class MysqlDemo {
    public static void main1(String[] args) throws SQLException, ClassNotFoundException {
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/bdap","root","root");
        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery("SELECT *  FROM tbl_txt");
        int columnCount = resultSet.getMetaData().getColumnCount();
        while (resultSet.next()) {
            LinkedHashMap<String,Object> result = new LinkedHashMap<>();
            for (int i = 0; i < columnCount; i++) {
                int columnIndex = i +1;
                String key = resultSet.getMetaData().getColumnName(columnIndex);
                String columnClassName = resultSet.getMetaData().getColumnClassName(columnIndex);
                String columnTypeName = resultSet.getMetaData().getColumnTypeName(columnIndex);
                Object value = resultSet.getObject(columnIndex,Class.forName(columnClassName));
                if(columnTypeName.equalsIgnoreCase("blob")) {
                    value = null;
                    Blob blob = resultSet.getBlob(columnIndex);
                    if(blob != null) {
                        try (InputStream in = blob.getBinaryStream()) {
                            byte[] data = new byte[(int) resultSet.getBlob(columnIndex).length()];
                            in.read(data);
                            value = Base64.getEncoder().encodeToString(data);

                            /*FileOutputStream out = new FileOutputStream("d:/a.png");
                            //out.write(data);
                            out.write(Base64.getDecoder().decode(value.getBytes()));
                            out.flush();
                            out.close();*/
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                result.put(key,value);
            }
            System.out.println(result);
            System.out.println(JSON.toJSONString(result));
        }
    }
}
